<?php


namespace app\admin\controller\jizhan;


use app\admin\model\HtnsBasestationStore;
use app\admin\model\HtnsOrder;
use app\admin\model\HtnsOrderCartInfo;
use app\admin\model\HtnsUser;
use app\admin\traits\Curd;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use jianyan\excel\Excel;
use think\App;
use think\facade\Cache;

/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="基站线下订单")
 */
class OfflineOrder extends AdminController
{

    use Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new HtnsOrder();

        $this->assign('payType', $this->model->payType);
        $this->assign('orderStatus', $this->model->status);
        $storeId = session('admin')['store_id'];//当前用户门店id
        // 下单基站
        $where = [];
        if($storeId){
            $where['id'] = $storeId;
        }
        $htnsBasestationStore = HtnsBasestationStore::where($where)->select()->order('id desc')->toArray();
        $storeList            = array_column($htnsBasestationStore, 'name', 'id');
        $this->assign('storeList', $storeList);
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index($export = 0)
    {
        $storeId = session('admin')['store_id'];//当前用户门店id
        if ($this->request->isAjax() || $export) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 自定义搜索条件解析
            $whereArr = [];
            $filter   = input('filter');
            $filter = htmlspecialchars_decode($filter);// html特殊字符转化&quot;转换为'
            if ($filter) {
                $filterArr = json_decode($filter, true);
                if (isset($filterArr['storeName'])) {
                    $whereArr[] = ['store_id', '=', $filterArr['storeName']];
                }
                if (isset($filterArr['payType'])) {
                    $whereArr[] = ['pay_type', '=', $filterArr['payType']];
                }
                if (isset($filterArr['add_time'])) {
                    $time       = explode(' - ', $filterArr['add_time']);
                    $whereArr[] = ['add_time', 'between', [strtotime($time[0]), strtotime($time[1])]];
                }
                if (isset($filterArr['orderStatus'])) {
//                    $whereArr[] = ['status', '=', $filterArr['orderStatus']];
                    $whereArr[] = ['refund_status', '=', 0];
                    $whereArr[] = ['is_del', '=', 0];
                    if($filterArr['orderStatus'] == 0){
                        $whereArr[] = ['paid', '=', 0];
                        $whereArr[] = ['status', '=', 0];
                    }elseif ($filterArr['orderStatus'] == 1){
                        $whereArr[] = ['paid', '=', 1];
                        $whereArr[] = ['status', 'in',[0,1,2,3,4]];
                        $whereArr[] = ['refund_status', 'in',[0,1,2,3]];
                    }elseif ($filterArr['orderStatus'] == 2){
                        $whereArr[] = ['paid', '=', 1];
                        $whereArr[] = ['status', '=',1];
                        $whereArr[] = ['refund_status', 'in',[0,1,2,3]];
                    }elseif ($filterArr['orderStatus'] == 3){
                        $whereArr[] = ['paid', '=', 1];
                        $whereArr[] = ['status', '=',2];
                        $whereArr[] = ['refund_status', 'in',[0,1,2,3]];
                    }elseif ($filterArr['orderStatus'] == 4){
                        $whereArr[] = ['paid', '=', 1];
                        $whereArr[] = ['status', '=',3];
                        $whereArr[] = ['refund_status', 'in',[0,1,2,3]];
                    }
                }
            }
            if($storeId){
                $whereArr[] = ['store_id', '=', $storeId];
            }
            $whereArr[] = ['order_types','=','store'];
            $cacheWhereKey = 'offlineOrder';
            if($export){
                $page = 1;
                $limit = 10000;
                $cacheWhere = Cache::get($cacheWhereKey);
                if(!empty($cacheWhere)){
                    $whereArr = $cacheWhere;
                }
            }else{
                if(!empty($whereArr)){
                    $resc = Cache::set($cacheWhereKey , $whereArr , 3600 * 24);
                }
            }
//            halt($filter,$whereArr);
            if($export){
                $page = 1;
                $limit = 10000;
            }
            $count = $this->model
                ->where($whereArr)
                ->count();
            $list  = $this->model
                ->where($whereArr)
                ->page($page, $limit)
                ->order($this->sort)
//                ->fetchSql(true)
                ->select()->toArray();
//            halt($list);
            // 订单号|类型,用户昵称|ID|代理等级,商品名称,规格,购买数量,下单基站,下单时间,销售价,优惠金额,实际支付,返利积分,支付方式,订单 状态,完成时间
            $htnsUser = new HtnsUser();
            $ret = [];
            foreach ($list as $v) {
                $type                  = $this->model->getOrderType($v);
                $retv['id']       = $v['id'];
                $retv['orderSn']       = $v['order_id'] . '<br/>' . $type;
                $user                  = HtnsUser::find($v['uid']);
                $level                 = $htnsUser->getGradeName($user['jmyc_grade']);
                $retv['userInfo']      = $user['real_name'] . '|' . $v['uid'] . '|' . $level;
                $retv['productInfo']   = '';
                $retv['storeName']     = '';
                $retv['add_time']      = empty($v['add_time']) ? '' : date('Y-m-d H:i:s', $v['add_time']);
                $retv['price']         = 0;
                $retv['pay_price']     = $v['pay_price'];
                $retv['gain_integral'] = $v['gain_integral'];
                $retv['payType']       = $this->model->getPayType($v['pay_type']);
                $retv['orderStatus']   = $this->model->getStatus($v);
                // 查询商品详情
                $wherec['oid']     = $v['id'];
                $htnsOrderCartInfo = HtnsOrderCartInfo::where($wherec)->select()->toArray();
                $str               = '';
                foreach ($htnsOrderCartInfo as $vc) {
                    $cartInfo      = json_decode($vc['cart_info'], true);
                    $productInfo   = $cartInfo['productInfo'];
                    $attrInfo      = $cartInfo['attrInfo'];
                    $str           .= sprintf('%s|%s|%s|<br/>', $productInfo['store_name'], $attrInfo['suk'],
                        $cartInfo['truePrice'] . 'x' . $cartInfo['cart_num']);
                    $retv['price'] += $cartInfo['sum_price'];
                }
                $retv['productInfo']     = $str;
                $retv['deduction_price'] = bcsub($retv['price'], $retv['pay_price'], 2);
                // 下单基站
                $store = HtnsBasestationStore::find($v['store_id']);
                if ($store) {
                    $retv['storeName'] = $store['name'];
                }
                $ret[] = $retv;
            }
            $list = $ret;
            // 导出
            if($export){
                return $list;
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {

//        list($page, $limit, $where) = $this->buildTableParames();
//        $tableName = 'mall_cate';
////        $tableName = CommonTool::humpToLine(lcfirst($tableName));
//        $prefix = config('database.connections.mysql.prefix');
//        $dbList = \think\facade\Db::query("show full columns from {$prefix}{$tableName}");
//        $header = [];
//        foreach ($dbList as $vo) {
//            $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
//            if (!in_array($vo['Field'], $this->noExportFields)) {
//                $header[] = [$comment, $vo['Field']];
//            }
//        }


        $header = [
            ['订单Id','id'],
            ['发货仓库','hcname'],
            ['订单类型','orderTypes'],
            ['订单号|类型','orderSn'],
            ['用户昵称|ID|代理等级','userInfo'],
            ['商品信息','productInfo'],
            ['商品名称','productName'],
            ['商品规格','productAttr'],
            ['商品数量','productNum'],
            ['商品售价','productPrice'],
            ['下单基站','storeName'],
            ['下单时间','add_time'],
            ['销售价','price'],
            ['优惠金额','deduction_price'],
            ['实际支付','pay_price'],
            ['返利积分','gain_integral'],
            ['支付方式','payType'],
            ['订单状态','orderStatus'],
            ['物流状态','expressStatus'],
            ['买家信息','buyerInfo'],
            ['收货人信息','receiverInfo'],
            ['售后状态','refundStatus'],
        ];
        // 根据商品拆分数据再进行合并
        $list = $this->index(1);
        $ret = [];
        // 订单多个商品数据合并处理
        $hh = '<br/>';
        foreach ($list as $v) {
            $v['orderSn'] = str_replace($hh,'',$v['orderSn']);
            $v['productInfo'] = rtrim($v['productInfo'] , $hh);
            $productArr = explode($hh , $v['productInfo']);

            $retv = $v;
            $retv['is_merge'] = 0;
            if(count($productArr) > 1){
                foreach ($productArr as $kp => $vp) {
                    $retv['productInfo'] = $vp;
                    $productInfoArr = explode('|',$vp);
                    $retv['productName'] = $productInfoArr[0];
                    $retv['productAttr'] = $productInfoArr[1];
                    $priceInfo = explode('x',$productInfoArr[2]);
                    $retv['productPrice'] = $priceInfo[0];
                    $retv['productNum'] = $priceInfo[1];
                    $retv['is_merge'] = 0;
                    if($kp == 0){
                        $retv['is_merge'] = 1;// 第一行合并,其它行默认
                    }
                    $ret[] = $retv;
                }
            }else{
                $productInfoArr = explode('|',$v['productInfo']);
                $retv['productName'] = $productInfoArr[0];
                $retv['productAttr'] = $productInfoArr[1];
                $priceInfo = explode('x',$productInfoArr[2]);
                $retv['productPrice'] = $priceInfo[0];
                $retv['productNum'] = $priceInfo[1];
                $ret[] = $retv;
            }

//            if($productArr && count($productArr) > 1){
//                foreach ($productArr as $kp => $vp) {
//                    foreach ($list as $vl) {
//                        $retv = $vl;
//                        $retv['is_merge'] = 0;
//                        $retv['productInfo'] = $vp;
//                        $productInfoArr = explode('|',$vp);
//                        $retv['productName'] = $productInfoArr[0];
//                        $retv['productAttr'] = $productInfoArr[1];
//                        $priceInfo = explode('x',$productInfoArr[2]);
//                        $retv['productPrice'] = $priceInfo[0];
//                        $retv['productNum'] = $priceInfo[1];
//
//                        if($kp == 0){
//                            $retv['is_merge'] = 1;// 第一行合并,其它行默认
//                        }
//                        $ret[] = $retv;
//                    }
//                }
//            }else{
//                $retv = $v;
//                $retv['is_merge'] = 0;
//                $ret[] = $retv;
//            }
        }
        if($ret){
            $list = $ret;
        }
//        halt($ret);
//        halt($list);
        $fileName = time();
        $arrA = ['A','B','C','D','E','F'];
        $arrB = ['K','L','M','N','O','P','Q','R','S','T','U','V'];
        return Excel::exportData($list, $header, $fileName, 'xlsx','',[],$arrA,$arrB);
    }
}